package rabbitmq.routing;

import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import rabbitmq.constant.Constants;

import javax.naming.NamingException;
import javax.naming.ldap.Control;
import javax.naming.ldap.ControlFactory;
import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 *
 *  路由模式
 */
public class Producer {
    public static void main(String[] args) throws IOException, TimeoutException {
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost(Constants.HOST);
        factory.setPort(Constants.PORT);
        factory.setUsername(Constants.USER_NAME);
        factory.setPassword(Constants.PASSWORD);
        factory.setVirtualHost(Constants.VIRTUAL);

        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();
        // 生命交换机
        channel.exchangeDeclare(Constants.ROUTING_EXCHANGE, BuiltinExchangeType.DIRECT, true, false, false, null);
        // 声明队列
        channel.queueDeclare(Constants.ROUTING_QUEUE1, true, false, false, null);
        channel.queueDeclare(Constants.ROUTING_QUEUE2, true, false, false, null);
        // 交换机绑定队列
        channel.queueBind(Constants.ROUTING_QUEUE1, Constants.ROUTING_EXCHANGE, "a");
        channel.queueBind(Constants.ROUTING_QUEUE2, Constants.ROUTING_EXCHANGE, "a");
        channel.queueBind(Constants.ROUTING_QUEUE2, Constants.ROUTING_EXCHANGE, "b");
        channel.queueBind(Constants.ROUTING_QUEUE2, Constants.ROUTING_EXCHANGE,  "c");
        // 发送消息s
        String msgA = "hello routing A";
        channel.basicPublish(Constants.ROUTING_EXCHANGE, "a", true, false, null, msgA.getBytes());
        String msgB = "hello routing B";
        channel.basicPublish(Constants.ROUTING_EXCHANGE, "b", true, false, null, msgB.getBytes());
        String msgC = "hello routing C";
        channel.basicPublish(Constants.ROUTING_EXCHANGE, "c", true, false, null, msgC.getBytes());
        System.out.println("发送成功");
        // 释放资源
        channel.close();
        connection.close();
    }
}
